package auth

import (
	"net/http"

	"gitee.com/micro-plat/sas/sas/modules/auth/conf"
	"gitee.com/micro-plat/sas/sas/modules/const/enum"
	"gitee.com/micro-plat/sas/sas/modules/decrypt"
	"gitee.com/micro-plat/sas/sas/modules/sign"
	"github.com/micro-plat/lib4go/errs"
)

//DynamicAuth 动态认证
func (a *Auth) DynamicAuth(input map[string]interface{}, conf *conf.AuthConfig, type1, type2 string) (data map[string]interface{}, err error) {

	//检查参数及配置
	euid, signName, encodeKey, err := a.check(input, conf, type1, type2, enum.Dynamic)
	if err != nil {
		return
	}

	//获取密钥
	signKey, signRsaType, decryptKey, decryptRsaType, err := a.getSecret(type1, type2, euid, encodeKey, enum.Dynamic)
	if err != nil {
		return
	}

	//验证签名
	b, err := sign.Verify(input, signKey, signName, type1, signRsaType, conf)
	if err != nil || !b {
		err = errs.NewErrorf(http.StatusForbidden, "签名认证未通过 %+v", err)
		return
	}

	//获取加密数据
	encrypt := conf.GetEncryptData(input)
	if len(encrypt) < 1 {
		return
	}

	//解密数据
	innerData, err := decrypt.DecryptDataMap(encrypt, type2, decryptKey, decryptRsaType, conf)
	if err != nil {
		return
	}

	//替换加密字段
	data = replaceEncrypt(input, innerData)
	return
}

//replaceEncrypt 将参数中的密文替换为解密后的明文
func replaceEncrypt(input map[string]interface{}, decrypt map[string]string) map[string]interface{} {
	for dk, dv := range decrypt {
		if _, ok := input[dk]; ok {
			input[dk] = dv
		}
	}

	return input
}
